package com.ljyhhh.SmartCity.activity.updatePwd

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.alibaba.fastjson.JSONObject
import com.ljyhhh.SmartCity.R
import com.ljyhhh.SmartCity.activity.fragment.login.FragmentLogin
import kotlinx.android.synthetic.main.activity_update_password.*
import okhttp3.*
import java.io.IOException

class UpdatePasswordActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_update_password)
        update_pwd_button.setOnClickListener{
            val update_uname=update_uname.text.toString()
            val update_pwd=update_pwd.text.toString()
            val update_pwd_repeat=update_pwd_repeat.text.toString()

            if(update_pwd.isNotEmpty()&& update_uname.isNotEmpty() ) {
                if (update_pwd != update_pwd_repeat) {
                    Toast.makeText(this, "请检查两次输入密码是否相同", Toast.LENGTH_SHORT).show()
                }else{
                    updatePassword(update_uname, update_pwd)
                }

            }
            else
                Toast.makeText(this,"请输入账号或密码",Toast.LENGTH_SHORT).show()

        }
    }
    fun updatePassword(username:String,password: String){
        Thread{
            val requestBody= FormBody.Builder()
                .add("studentNumber",username)
                .add("password",password)
                .build()
            val requests= Request.Builder()
                .url("http://8.137.8.86/api/student/updatePassword")
                .post(requestBody)
                .build()
            OkHttpClient().newCall(requests)
                .enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        Toast.makeText(applicationContext, "发生错误", Toast.LENGTH_SHORT).show()
                    }

                    override fun onResponse(call: Call, response: Response) {
                        val res = response.body?.string()
                        val root = JSONObject.parseObject(res)
                        val code = root.getBooleanValue("success")
                        runOnUiThread {
                            updatePasswordToast(code)
                        }



                    }
                })
        }.start()

    }
    fun updatePasswordToast(code:Boolean){
        if(code){
            Toast.makeText(applicationContext, "修改密码成功", Toast.LENGTH_SHORT).show()
            startActivity(Intent(this, FragmentLogin::class.java))
        }else{
            Toast.makeText(applicationContext, "修改密码失败", Toast.LENGTH_SHORT).show()
            update_pwd.text.clear()
            update_uname.text.clear()
        }
    }
}